package io.itit.ecp.data;

import io.itit.ecp.admin.common.enums.IMeterDeviceEnums;
import io.itit.ecp.admin.provide.helper.CarbonEmissionFactorHelper;
import io.itit.ecp.admin.provide.helper.DataRangeHelper;
import io.itit.ecp.admin.server.entity.EnergyDataEntity;
import io.itit.ecp.admin.server.entity.MeterDeviceEntity;
import io.itit.ecp.admin.server.service.IEnergyDataService;
import io.itit.ecp.admin.server.service.IMeterDeviceService;
import io.itit.grass.common.server.helper.ThreadPoolHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Component
public class EnergyDataGenerate {

    @Resource
    private DataRangeHelper dataRangeHelper;

    @Resource
    private ThreadPoolHelper threadPoolHelper;

    @Resource
    private IEnergyDataService energyDataService;

    @Resource
    private IMeterDeviceService materDeviceService;

    @Resource
    private CarbonEmissionFactorHelper carbonEmissionFactorHelper;

    private static final Set<String> keySet = new HashSet<>();

    private List<MeterDeviceEntity> list() {
        return dataRangeHelper.approve(() -> materDeviceService.lambdaQuery()
                .eq(MeterDeviceEntity::getDelFlag, IMeterDeviceEnums.DelFlag.delFlag1.delFlag)
                .list());
    }

    //    @Scheduled(cron = "0 2 0/1 * * ?")
//    @PostConstruct
    public void generate() {
        threadPoolHelper.execute(() -> saveBatchAndClearList(generate(date(), list())));
    }

    //    @PostConstruct
    public void generateEnergyDataHistory() {

//        // 调用list()方法，获取MeterDeviceEntity类型的列表
//        List<MeterDeviceEntity> meterDeviceList = list();
//
//        // 如果meterDeviceList为空，则直接返回
//        if (CollectionUtils.isEmpty(meterDeviceList)) {
//            return;
//        }
//
//        // 定义一个名为entityList的EnergyDataEntity类型的列表
//        List<EnergyDataEntity> entityList = new ArrayList<>();
//
//        // 获取当前日期
//        Date date = date();
//
//        // 使用线程池执行任务
//        threadPoolHelper.execute(() -> {
//            // 使用IntStream.range生成1到2160的整数流
//            IntStream.range(0, 100).forEach(t -> {
//                // 调用generate方法，生成EnergyDataEntity类型的列表，并添加到entityList中
//                entityList.addAll(generate(DateUtils.addHours(date, -t), meterDeviceList));
//
//                // 使用IntStream.range生成1到3的整数流
//                IntStream.range(1, 4).forEach(y -> {
//                    // 调用generate方法，生成EnergyDataEntity类型的列表，并添加到entityList中
//                    entityList.addAll(generate(DateUtils.addYears(DateUtils.addHours(date, -t), -y), meterDeviceList));
//                });
//
//                saveBatchAndClearList(entityList);
//            });
//        });
    }

    /**
     * 保存数据并清空集合数据
     *
     * @param entityList
     */
    private void saveBatchAndClearList(List<EnergyDataEntity> entityList) {
//        // 如果entityList为空,直接返回
//        if (CollectionUtils.isEmpty(entityList)) {
//            return;
//        }
//        dataRangeHelper.approve(() -> {
//            // 使用energyDataService进行数据操作
//            energyDataService.lambdaUpdate()
//                    // 使用in方法，根据solidifyDate字段进行筛选
//                    .in(EnergyDataEntity::getSolidifyDate, entityList.stream().map(EnergyDataEntity::getSolidifyDate).collect(Collectors.toSet()))
//                    // 调用remove方法，删除符合条件的数据
//                    .remove();
//
//            // 调用saveBatch方法，批量保存entityList中的数据，每次保存1000条
//            energyDataService.saveBatch(entityList, 1000);
//
//            // 清空entityList
//            entityList.clear();
//            return entityList;
//        });
    }

    public List<EnergyDataEntity> generate(Date date, List<MeterDeviceEntity> meterDeviceList) {

//        String dateStr = Y666Utils.format(date, "yyyy-MM-dd HH:mm:ss");
//
//        log.info("生成{}数据", dateStr);
//
//        List<EnergyDataEntity> entityList = new ArrayList<>();
//
//        for (MeterDeviceEntity meterDevice : meterDeviceList) {
//            EnergyDataEntity energyData = build(meterDevice);
//            energyData.setReadTime(date);
//            energyData.setSolidifyDate(date);
//            energyData.setDeviceCode(meterDevice.getDeviceCode());
//            energyData.setDeviceName(meterDevice.getDeviceName());
//            energyData.setEnergyTypeId(meterDevice.getEnergyTypeId());
//            energyData.setMeterValue(random());
//            energyData.setReadValue(energyData.getMeterValue());
//            Pair<BigDecimal, String> pair = carbonEmissionFactorHelper.calc(energyData.getEnergyTypeId(), date, energyData.getMeterValue());
//            energyData.setCarbonEmission(pair.getKey());
//            energyData.setCarbonEmissionProcess(pair.getValue());
//            energyData.setReadType(IEnergyDataEnums.ReadType.readType2.readType);
//
//            String key = energyData.getMeterDeviceId() + dateStr;
//            if (!keySet.contains(key)) {
//                keySet.add(key);
//                entityList.add(energyData);
//            } else {
//                log.info("重复数据：{}", key);
//            }
//        }
//
//        return entityList;
        return Collections.emptyList();
    }

    public EnergyDataEntity build(MeterDeviceEntity meterDevice) {
        EnergyDataEntity entity = new EnergyDataEntity();
        entity.setEnergyTypeId(meterDevice.getEnergyTypeId());
        entity.setSceneEdificeId(meterDevice.getSceneEdificeId());
        entity.setSceneFloorId(meterDevice.getSceneFloorId());
        entity.setSceneRoomId(meterDevice.getSceneRoomId());
//        entity.setSceneCompanyId(meterDevice.getSceneCompanyId());
        entity.setMeterDeviceId(meterDevice.getId());
        entity.setSceneProjectId(meterDevice.getSceneProjectId());
        entity.setMeterType(meterDevice.getMeterType());
        entity.setReadMeterTag(meterDevice.getReadMeterTag());
        entity.setReadMeterType(meterDevice.getReadMeterType());
        entity.setPurpose(meterDevice.getPurpose());
        return entity;
    }

    public static BigDecimal random() {
        Random random = new Random();
        return new BigDecimal(random.nextInt(1000) + 1);
    }

    public static Date date() {
        Date date = new Date();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        return calendar.getTime();
    }

}
